package com.atguigu.gmall.product.controller;

import com.atguigu.gmall.common.result.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.io.FilenameUtils;
import org.csource.common.MyException;
import org.csource.fastdfs.*;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.util.ClassUtils;

import java.io.IOException;

/**
 * @ author     ：廖传港
 * @ date       ：Created in 2020/12/22 16:13
 * @ description：文件上传，图片
 * @ modified By：
 * @ ersion:
 */
@Api(description = "图片上传")
@RestController
@RequestMapping("admin/product")
public class FileController {

    @Value("${img.url}")
    private String imgurl;

    @ApiOperation("上传图片")
    @PostMapping("fileUpload")
    public Result fileUpload(MultipartFile file) {

        String path = ClassUtils.getDefaultClassLoader().getResource("fdfs_client.conf").getPath();
        try {
            ClientGlobal.init(path);
            TrackerClient trackerClient = new TrackerClient();
            TrackerServer trackerServer = trackerClient.getConnection();
            StorageServer storageServer = null;
            StorageClient1 storageClient1 = new StorageClient1(trackerServer, storageServer);
            String ext = FilenameUtils.getExtension(file.getOriginalFilename());
            String p = storageClient1.upload_file1(
                    file.getBytes(),
                    ext, null);
            System.out.println(imgurl + p);
            return Result.ok(imgurl+p);
        } catch (IOException e) {
            e.printStackTrace();
        } catch (MyException e) {
            e.printStackTrace();
        }


        return null;
    }

}
